<template>
  <div class="container">
    <div class="filter-container">
      <!-- 园区选择器 -->
      <el-select
        v-model="selectedSchool"
        placeholder="请选择园区"
        @change="handleSchoolChange"
        class="filter-select"
      >
        <el-option
          v-for="school in schoolList"
          :key="school.id"
          :label="school.name"
          :value="school.id"
        />
      </el-select>

      <!-- 年份选择器 -->
      <el-select
        v-model="selectedYear"
        placeholder="请选择年份"
        @change="handleYearChange"
        class="filter-select"
      >
        <el-option v-for="year in yearList" :key="year" :label="year + '年'" :value="year" />
      </el-select>
    </div>

    <!-- 表格容器 -->
    <div class="table-container">
      <template v-if="weekData.length > 0">
        <!-- 表头 -->
        <div class="table-header">
          <div class="header-cell header-class">
            <span class="time-text">时间</span>
            <span class="class-text">班级</span>
            <span class="room-text">{{ roomTypeLabel }}</span>
          </div>

          <div class="header-cell header-room" v-for="(room, index) in roomList" :key="index">
            {{ room.name }}
          </div>
        </div>

        <!-- 表格内容 -->
        <div class="table-body">
          <div class="row" v-for="(week, weekIndex) in weekData" :key="weekIndex">
            <div class="cell cell-time">{{ week.weeksName }}</div>
            <!-- <div class="cell cell-class">
              <div v-if="getRoomClass(week.id) && getRoomClass(week.id).length > 0">
                <el-tag
                  v-for="className in getRoomClass(week.id)"
                  :key="className"
                  type="primary"
                  class="class-tag"
                >
                  {{ className }}
                </el-tag>
              </div>
              <div v-else class="empty-cell">-</div>
            </div> -->
            <div class="cell cell-room" v-for="(room, roomIndex) in roomList" :key="roomIndex">
              <div
                v-if="
                  getRoomClassByRoom(week.id, room.id) &&
                  getRoomClassByRoom(week.id, room.id).length > 0
                "
              >
                <el-tag
                  v-for="className in getRoomClassByRoom(week.id, room.id)"
                  :key="className"
                  type="primary"
                  class="class-tag"
                >
                  {{ className }}
                </el-tag>
              </div>
              <div v-else class="empty-cell">-</div>
            </div>
          </div>
        </div>
      </template>

      <!-- 无数据状态 -->
      <el-empty v-else description="暂无排期数据" />
    </div>

    <!-- 景秀园区固定表格 -->
    <div v-if="selectedSchool === 1598022292" class="fixed-table-container">
      <table class="fixed-table">
        <tr>
          <th colspan="6" class="main-header">攀悦乐园</th>
        </tr>
        <tr>
          <th>时段</th>
          <th>周一</th>
          <th>周二</th>
          <th>周三</th>
          <th>周四</th>
          <th>周五</th>
        </tr>
        <tr>
          <td class="fixed-table-cell">上午</td>
          <td>
            <div>小一班</div>
          </td>
          <td>
            <div>小二班</div>
          </td>
          <td>
            <div>小三班</div>
          </td>
          <td>
            <div>小四班</div>
          </td>
          <td>
            <div>小五班</div>
          </td>
        </tr>
        <tr>
          <td class="fixed-table-cell">下午</td>
          <td>
            <div
              >大一班 <br />
              14:50-15:40</div
            >
            <el-divider />
            <div
              >中一班 <br />
              15:50-16:20</div
            >
          </td>
          <td>
            <div
              >大二班 <br />
              14:50-15:40</div
            >
            <el-divider />
            <div
              >中二班 <br />
              15:50-16:20</div
            >
          </td>
          <td>
            <div
              >大三班 <br />
              14:50-15:40</div
            >
            <el-divider />
            <div
              >中三班 <br />
              15:50-16:20</div
            >
          </td>
          <td>
            <div
              >大四班 <br />
              14:50-15:40</div
            >
            <el-divider />
            <div
              >中四班 <br />
              15:50-16:20</div
            >
          </td>
          <td>
            <div
              >大五班 <br />
              14:50-15:40</div
            >
            <el-divider />
            <div
              >中五班 <br />
              15:50-16:20</div
            >
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { RoomWeeksApi } from '@/api/school/room/weeks'
import { RoomApi } from '@/api/school/room'
import { ClassesApi } from '@/api/school/classes'

// 定义响应式数据
const selectedSchool = ref<number | undefined>(undefined)
const schoolList = ref<any[]>([])
const roomList = ref<any[]>([])
const weekData = ref<any[]>([])
const classList = ref<any[]>([])
const selectedYear = ref<number | undefined>(undefined)
const yearList = ref<number[]>([])

// 获取当前路由信息
const route = useRoute()

// 根据路径确定房间类型
const getRoomType = () => {
  if (route.path.includes('/school/room/game-zone/game-table')) {
    return '2' // 游戏区房间类型
  }
  // 默认为功能室房间类型
  return '1'
}

// 获取房间类型标签
const getRoomTypeLabel = () => {
  if (route.path.includes('/school/room/game-zone/game-table')) {
    return '游戏区'
  }
  // 默认为功能室
  return '功能室'
}

const roomType = getRoomType()
const roomTypeLabel = getRoomTypeLabel()

// 获取园区列表并提取功能室
const getSchoolList = async () => {
  try {
    const data = await RoomApi.getRoomList(roomType) // 根据路径动态设置房间类型
    schoolList.value = data.filter((item) => item.children && item.children.length > 0)
    // 提取所有功能室
    const allRooms = data.flatMap((school) => school.children || [])
    roomList.value = allRooms
    // 默认选中第一个园区
    if (schoolList.value.length > 0) {
      selectedSchool.value = schoolList.value[0].id
      await loadRoomAndWeekData(selectedSchool.value)
    }
  } catch (error) {
    console.error('获取园区列表失败:', error)
  }
}

// 获取功能室列表
const getRoomList = async () => {
  try {
    const data = await RoomApi.getRoomList(roomType) // 根据路径动态设置房间类型
    // 根据选中的园区过滤功能室
    if (selectedSchool.value) {
      const school = data.find((s) => s.id === selectedSchool.value)
      if (school && school.children) {
        roomList.value = school.children
      } else {
        roomList.value = []
      }
    } else {
      // 如果没有选中园区，显示所有功能室
      roomList.value = data.flatMap((school) => school.children || [])
    }
  } catch (error) {
    console.error('获取功能室列表失败:', error)
  }
}

// 获取年份列表（从周计划数据中提取）
const getYearList = async () => {
  try {
    const data = await RoomWeeksApi.getWeekScheduleList(roomType)
    const years = new Set(data.map((item) => item.weekYear))
    yearList.value = Array.from(years)
      .map((y) => parseInt(y as string))
      .sort((a, b) => b - a) // 降序排列
    // 默认选中最新年份（仅在未选择过年份时）
    if (!selectedYear.value && yearList.value.length > 0) {
      selectedYear.value = yearList.value[0]
    }
  } catch (error) {
    console.error('获取年份列表失败:', error)
  }
}

// 获取周计划列表（去重处理）
const getWeekScheduleList = async () => {
  try {
    // 确保selectedYear.value有值
    if (!selectedYear.value) {
      console.warn('年份未选择，无法获取周计划列表')
      return []
    }

    const data = await RoomWeeksApi.getWeekScheduleList(roomType) // 根据路径动态设置房间类型
    const weeksMap = new Map<string, any>() // 使用 Map 去重，以 weeksName 为 key
    for (const yearData of data) {
      // 只处理选中年份的数据
      if (yearData.weekYear === selectedYear.value.toString()) {
        for (const week of yearData.weeksList) {
          const key = week.weeksName
          if (!weeksMap.has(key)) {
            weeksMap.set(key, { ...week, id: week.id })
          }
        }
      }
    }
    return Array.from(weeksMap.values())
  } catch (error) {
    console.error('获取周计划列表失败:', error)
    return []
  }
}

// 获取指定周的详细排期数据
const getRoomScheduleListByWeekId = async (weekId: number) => {
  try {
    const data = await RoomWeeksApi.getRoomScheduleListByWeekId(weekId)
    if (!data?.length) {
      return []
    }
    const scheduleList: any = []
    data.forEach((item) => {
      item.roomIds.forEach((roomId) => {
        scheduleList.push({
          id: item.id,
          weekId: item.weekId,
          roomId: roomId,
          classIds: item.classIds
        })
      })
    })
    return scheduleList
  } catch (error) {
    console.error(`获取周 ${weekId} 的排期数据失败:`, error)
    return []
  }
}

// 加载园区对应的功能室和周计划数据
const loadRoomAndWeekData = async (schoolId: number | undefined) => {
  await getClassList()
  await getYearList() // 获取年份列表

  // 如果没有选中年份，则不继续加载
  if (!selectedYear.value) {
    weekData.value = []
    return
  }

  const weeks = await getWeekScheduleList()
  weekData.value = []

  // 逐个获取每个周的详细排期数据
  for (const week of weeks) {
    const scheduleList = await getRoomScheduleListByWeekId(week.id)
    // 过滤掉不属于已选园区的排期数据
    const filteredScheduleList = scheduleList.filter((schedule) => {
      const room = roomList.value.find((r) => r.id === schedule.roomId)
      return room !== undefined
    })

    if (filteredScheduleList.length > 0) {
      week.rooms = filteredScheduleList
      weekData.value.push(week)
    }
  }
}

// 处理园区切换
const handleSchoolChange = async (value: number | undefined) => {
  selectedSchool.value = value
  await getRoomList() // 重新获取功能室列表
  await loadRoomAndWeekData(value)
}

// 处理年份切换
const handleYearChange = async (value: number | undefined) => {
  selectedYear.value = value
  // 只有在已选择园区的情况下才加载数据
  if (selectedSchool.value) {
    await loadRoomAndWeekData(selectedSchool.value)
  } else {
    // 如果没有选择园区，至少更新周数据
    const weeks = await getWeekScheduleList()
    weekData.value = []

    // 逐个获取每个周的详细排期数据
    for (const week of weeks) {
      const scheduleList = await getRoomScheduleListByWeekId(week.id)
      if (scheduleList.length > 0) {
        week.rooms = scheduleList
        weekData.value.push(week)
      }
    }
  }
}

// 获取指定周的班级信息（多个班级）
const getRoomClass = (weekId: number): string[] => {
  const schedule = weekData.value
    .find((week) => week.id === weekId)
    ?.rooms?.find((room) => room.classIds)
  if (!schedule) return []
  return schedule.classIds.map((id) => {
    const cls = classList.value.find((c) => c.id === id)
    return cls ? cls.className : ''
  })
}

// 获取指定周和功能室的班级信息
const getRoomClassByRoom = (weekId: number, roomId: number): string[] => {
  const schedule = weekData.value
    .find((week) => week.id === weekId)
    ?.rooms?.find((room) => room.roomId === roomId)
  if (!schedule) return []
  return schedule.classIds.map((id) => {
    const cls = classList.value.find((c) => c.id === id)
    return cls ? cls.className : ''
  })
}

// 获取班级列表
const getClassList = async () => {
  try {
    classList.value = await ClassesApi.getClassesSimpleList()
  } catch (error) {
    console.error('获取班级列表失败:', error)
  }
}

// 初始化数据
onMounted(async () => {
  await getSchoolList()
  await getRoomList() // 初始化功能室列表
})
</script>
<style lang="scss" scoped>
// 响应式设计
@media (width <= 768px) {
  .table-container {
    overflow-x: auto;
  }

  .table-header,
  .row {
    flex-direction: column;
  }

  .header-cell,
  .cell {
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
  }

  .header-time,
  .header-class,
  .cell-time,
  .cell-class {
    width: auto;
  }

  .filter-container {
    flex-direction: column;
  }

  .filter-select {
    width: 100%;
  }
}

.container {
  padding: 20px;
  font-size: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgb(0 0 0 / 5%);
}

.filter-container {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-select {
  width: 200px;
}

.table-container {
  position: relative;
  width: 100%;
  min-height: fit-content;
  margin-bottom: 20px;
  border-collapse: collapse;
}

.table-header {
  display: flex;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.header-cell {
  padding: 12px 8px;
  text-align: center;
  border-top: 1px solid #e4e7ed;
  border-right: 1px solid #e4e7ed;
}

.header-time {
  width: 150px;
}

.header-class {
  position: relative;
  display: flex;
  width: 150px;
  height: 50px;
  font-size: 14px;
  text-align: center;
  border-right: 1px solid #e4e7ed;
  align-items: center;
  justify-content: center;
  border-left: 1px solid #e4e7ed;
}

// 斜线样式
.header-class::before {
  position: absolute;
  z-index: 1;
  width: 1px;
  height: 100px;
  background-color: #e4e7ed;
  content: '';
  transform: rotate(-60deg);
  inset: 0;
  transform-origin: top;
}

.header-class::after {
  position: absolute;
  z-index: 1;
  width: 1px;
  height: 152px;
  background-color: #e4e7ed;
  content: '';
  transform: rotate(284deg);
  inset: 0;
  transform-origin: top;
}
// 时间文本
.header-class .time-text {
  position: absolute;
  bottom: 2px;
  left: 10px;
  z-index: 2;
  color: #333;
  text-align: center;
}

// 班级文本
.header-class .class-text {
  position: absolute;
  right: 35px;
  bottom: 2px;
  z-index: 2;
  color: #333;
  text-align: center;
}

.header-class .room-text {
  position: absolute;
  top: 2px;
  right: 5px;
  z-index: 2;
  color: #333;
  text-align: center;
}

.header-room {
  flex: 1;
  min-width: 150px;
}

.table-body {
  display: flex;
  flex-direction: column;
}

.row {
  display: flex;
  border-bottom: 1px solid #e4e7ed;

  &:hover {
    background-color: #ecf5ff;
  }
}

.cell {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 50px;
  padding: 12px 8px;
  text-align: center;
  border-right: 1px solid #e4e7ed;
}

.cell-time {
  width: 150px;
  background-color: #f5f7fa;
  border-left: 1px solid #e4e7ed;
}

.cell-class {
  width: 150px;
  background-color: #f5f7fa;
}

.cell-room {
  flex: 1;
  min-width: 150px;
}

// 标签样式
.class-tag {
  margin: 2px;
  font-size: 12px;
}

.empty-cell {
  font-style: italic;
  color: #999;
}

// Empty状态样式
:deep(.el-empty) {
  padding: 40px 0;
}

// 景秀园区固定表格样式
.fixed-table-container {
  margin-top: 30px;
  overflow-x: auto;
}

.fixed-table {
  width: 100%;
  font-size: 14px;
  text-align: center;
  border-collapse: collapse;
}

.fixed-table .main-header {
  padding: 15px;
  font-size: 16px;
  font-weight: 400;
  background-color: #f5f7fa;
  // color: white;
}

.fixed-table th,
.fixed-table .fixed-table-cell {
  background-color: #f5f7fa;
}

.fixed-table th,
.fixed-table td {
  padding: 10px;
  font-weight: 400;
  vertical-align: middle;
  border: 1px solid #e4e7ed;
}

.fixed-table td div {
  margin: 3px 0;
}

// .fixed-table tr:nth-child(even) {
//   background-color: #f5f7fa;
// }

// .fixed-table tr:nth-child(odd) {
//   background-color: #fff;
// }

.fixed-table tr:hover {
  background-color: #ecf5ff;
}
</style>
